package ac.il.technion.cs236635.project.test;

import ac.il.technion.cs236635.project.core.Server;

import ac.il.technion.cs236635.project.core.generated.Dispatcher;
import ac.il.technion.cs236635.project.core.generated.DispatcherService;
import ac.il.technion.cs236635.project.core.generated.ServerInfo;

public class ServerMain {
	private static final int PORT_BASE = 8080;
	private static final String URL_BASE = "http://localhost";
	private static final String SERVER_URI = "Server";

	private static int id;

	public static void main(String[] args)
	{
		if (args.length != 1)
		{
			System.err.println("Usage: server <SERVER-ID>");
			System.err.println("\tServer is published on " + URL_BASE +
				":<PORT>/" + SERVER_URI);
			System.err.println("\tWhere <PORT> is " + PORT_BASE +
					"<SERVER-ID>");
			return;
		}

		id = Integer.parseInt(args[0]);

		String url = URL_BASE + ":" + (PORT_BASE + id) + "/" + SERVER_URI;

		System.out.println("Running server " + id + " on " + url);
		Server server = new Server(url);
		server.start();

		DispatcherService ds = new DispatcherService();
		Dispatcher d = ds.getDispatcherPort();

		System.out.println("Registering server " + id + " to " +
				ds.getServiceName());
		ServerInfo si = new ServerInfo();
		si.setServerEnpoint(server.getEndpoint());
		si.setServerName(server.getName());
		d.register(si);

		try {
			server.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.println("Server " + id + " died");
	}
}